import {Injectable} from '@angular/core';
import {Action, State, StateContext} from "@ngxs/store";
import {Shop} from "./shop.actions";
import * as _ from 'lodash'

export interface ShopModel {
  list: Shop[]
}

@State<ShopModel>({
  name: 'shop',
  defaults: {
    list: []
  }
})
@Injectable({
  providedIn: 'root'
})
export class ShopState {

  constructor() {
  }

  @Action(Shop.Get)
  get({getState, patchState}: StateContext<ShopModel>) {
    let shops = getState().list;
    if (!!shops && !!shops.length) {
      return
    }
    patchState({
      list: [
        {id: 1, name: '卫龙辣条', price: 0.5},
        {id: 2, name: '小浣熊干脆面', price: 1},
        {id: 3, name: '康师傅牛肉面', price: 2},
      ]
    })
  }

  @Action(Shop.Add)
  add({patchState, getState}: StateContext<ShopModel>, {payload}: Shop.Add) {
    if (!payload.id) {
      payload.id = new Date().getTime()
    }
    patchState({
      list: getState().list.concat(payload)
    })
  }

  @Action(Shop.Remove)
  remove({patchState, getState}: StateContext<ShopModel>, {id}: Shop.Remove) {
    let list = getState().list;
    list = _.filter(list, s => s.id != id)
    patchState({
      list: list
    })
  }

  @Action(Shop.Update)
  update({patchState, getState}: StateContext<ShopModel>, {payload}: Shop.Update) {
    let list = JSON.parse(JSON.stringify(getState().list));
    for (let shop of list) {
      if (shop.id === payload.id) {
        _.assign(shop, payload)
        break
      }
    }
    patchState({
      list: list
    })
  }
}
